package com.wolfpire.system.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.wolfpire.system.common.Constants;
import com.wolfpire.system.common.Page;
import com.wolfpire.system.common.base.dao.impl.BaseHibernateDao;
import com.wolfpire.system.dao.RoleDao;
import com.wolfpire.system.dao.UserGroupDao;
import com.wolfpire.system.model.Role;
import com.wolfpire.system.model.UserGroup;
import com.wolfpire.system.model.UserGroupUserRelation;

@Repository("userGroup")
public class UserGroupDaoImpl extends BaseHibernateDao<UserGroup, Long> implements UserGroupDao {

	public List<UserGroup> list(UserGroup userGroup) {
		Criteria c = createCriteria(createFilter(userGroup));
		return c.list();
	}

	private Criterion[] createFilter(UserGroup userGroup) {
		List<Criterion> criterions = new ArrayList<Criterion>();
		
		if (null != userGroup.getId()) {
			criterions.add(Restrictions.eq("id", userGroup.getId()));
		}
		if (!StringUtils.isBlank(userGroup.getName())) {
			criterions.add(Restrictions.like("name", userGroup.getName(), MatchMode.ANYWHERE));
		}
		return criterions.toArray(new Criterion[criterions.size()]);
	}

	public Page<UserGroup> findUserGroups(Page<UserGroup> page,
			UserGroup filterUserGroup) {
		Criterion[] criterions = createFilter(filterUserGroup);
		int totalCount = this.findIntByCriteria(criterions);
		page.setTotalCount(totalCount);
		
		if (0 < totalCount) {
			Criteria c = createCriteria(criterions);
			c = this.setPageParameter(c, page);
			@SuppressWarnings({ "unchecked" })
			List<UserGroup> result = c.list();
			page.setDataList(result);
		}
		return page;
	}

	public String findUserGroupNames(List<Long> userGroupsId) {
		// TODO Auto-generated method stub
		return null;
	}

	public String getUserIdsByUserGroupId(Long userGroupId) {
		// TODO Auto-generated method stub
		return null;
	}
	/**
	 * 根据用户的ID，查找用户关联的用户组
	 */
	public List<UserGroup> findUserGroupByUserId(long userId) {
		StringBuffer querySql = new StringBuffer();
		List<String> propertyNames = new ArrayList<String>();
		List propertyValues = new ArrayList();
		querySql.append(" select ug.* from t_sm_usergroup ug,t_usergroup_user ugs  ");
		querySql.append(" where ug.id = ugs.usergroup_id and ugs.user_id = :userId  ");
		propertyNames.add("userId");
		propertyValues.add(userId);
		SQLQuery query = this.createSqlQuery(querySql.toString(), propertyNames, propertyValues);
		query.addEntity(UserGroup.class);
		return query.list();
	}
	
}
